#!/bin/bash
# HoneyBadger BFT 编译脚本
# 使用真实密码学（Kyber + Edwards25519）

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  HoneyBadger BFT 编译脚本${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 显示帮助
show_help() {
    echo "用法: ./build.sh [选项]"
    echo ""
    echo "选项:"
    echo "  build    - 编译项目（默认）"
    echo "  clean    - 清理编译产物"
    echo "  help     - 显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  ./build.sh            # 编译项目"
    echo "  ./build.sh build      # 编译项目"
    echo "  ./build.sh clean      # 清理产物"
    echo ""
}

# 编译项目
build() {
    echo -e "${YELLOW}编译 HoneyBadger BFT...${NC}"
    echo "  - 密码学: ✅ 真实（Kyber + Edwards25519）"
    echo "  - 用途: 生产部署、安全测试"
    echo ""
    
    echo -e "${BLUE}[1/2] 编译主程序...${NC}"
    go build -o honeybadger cmd/main.go
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ honeybadger 编译成功${NC}"
    else
        echo -e "${RED}✗ 编译失败${NC}"
        exit 1
    fi
    
    echo -e "${BLUE}[2/2] 编译测试网络...${NC}"
    go build -o test_network test_network.go
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ test_network 编译成功${NC}"
    else
        echo -e "${RED}✗ 编译失败${NC}"
        exit 1
    fi
    
    echo ""
    echo -e "${GREEN}✅ 编译完成${NC}"
    echo ""
    echo "运行: ./test_network"
    echo ""
}

# 清理编译产物
clean() {
    echo -e "${YELLOW}清理编译产物...${NC}"
    
    rm -f honeybadger test_network
    
    echo -e "${GREEN}✓ 清理完成${NC}"
    echo ""
}

# 检查Go环境
check_go() {
    if ! command -v go &> /dev/null; then
        echo -e "${RED}错误: 未找到Go编译器${NC}"
        echo "请先安装Go: https://golang.org/dl/"
        exit 1
    fi
    
    GO_VERSION=$(go version | awk '{print $3}')
    echo -e "${GREEN}✓ Go环境正常: $GO_VERSION${NC}"
    echo ""
}

# 显示编译结果
show_results() {
    echo ""
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}  编译结果${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""
    
    if [ -f "honeybadger" ]; then
        SIZE=$(ls -lh honeybadger | awk '{print $5}')
        echo -e "${GREEN}✓${NC} honeybadger      ($SIZE)"
    fi
    
    if [ -f "test_network" ]; then
        SIZE=$(ls -lh test_network | awk '{print $5}')
        echo -e "${GREEN}✓${NC} test_network     ($SIZE)"
    fi
    
    echo ""
}

# 主逻辑
main() {
    MODE="${1:-build}"
    
    case "$MODE" in
        build|"")
            check_go
            build
            show_results
            ;;
        clean)
            clean
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            echo -e "${RED}错误: 未知选项 '$MODE'${NC}"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@"
